package com.su.lightthings.service

import android.app.Notification
import android.service.notification.NotificationListenerService
import android.service.notification.StatusBarNotification
import android.util.Log
import com.su.lightthings.bluetooth.BtUtil
import com.su.lightthings.bluetooth.ProtocolDataUtil
import com.su.lightthings.utils.ByteUtils
import com.su.lightthings.utils.Cons
import com.su.lightthings.viewmodel.BleViewModel
import com.su.lightthings.viewmodel.DataViewModel

class MyNotificationListenerService : NotificationListenerService() {

    private val TAG = "MyNotificationListenerS"
    private val dataViewModel = DataViewModel.INSTANCE

    override fun onNotificationPosted(sbn: StatusBarNotification?) {
        super.onNotificationPosted(sbn)
        val packageName = sbn?.packageName
        val title = sbn?.notification?.extras?.getString(Notification.EXTRA_TITLE)
        val content = sbn?.notification?.extras?.getString(Notification.EXTRA_TEXT)
        val postTime = sbn?.postTime
        val key = sbn?.key
        Log.d(
            TAG,
            "监听到消息: pckageName： $packageName >  title: $title >  content: $content >  key: $key  > postTime: $postTime"
        )
        //消息通知关闭,不做任何处理
        if (!dataViewModel.notifySwitch) return

        //获取App索引
        val id = -1
//        val id = Cons.FunctionItemList.notificationIndexMap[packageName] ?: -1
        //非需求的消息
        if (id == -1) return
        //判断该App开关是否开启
//        if (DataViewModel.INSTANCE.appNotify[id].state) {
//            if (title == null || content == null)
//                return
//            val mContent = if (content.length > 40) {
//                content.substring(0 until 40).plus("...")
//            } else {
//                content
//            }
//            sendToWatch(id, postTime ?: 0L, title, mContent)
//        }
    }

    override fun onNotificationRemoved(sbn: StatusBarNotification?) {
        super.onNotificationRemoved(sbn)
        Log.d(TAG, "onNotificationRemoved")
    }

    private fun sendToWatch(id: Int, timeStamp: Long, title: String, msg: String) {
        val data = ProtocolDataUtil.notifyMsg(id, timeStamp, title, msg)
        val message = BtUtil.makeWriteData(
            functionId = Cons.PushFunctionId.PUSH_MESSAGE,
            data = data
        )
        Log.d(
            TAG,
            "收到的内容: $id  $timeStamp  $title  $msg  \n 发送给手表: ${
                ByteUtils.toHexString(message)
            }"
        )
        BleViewModel.INSTANCE.write(message)
    }
}